package woodstock;

import java.io.File;

import javax.xml.stream.*;

import org.codehaus.stax2.XMLInputFactory2;
import org.codehaus.stax2.XMLStreamReader2;
import org.codehaus.stax2.validation.XMLValidationSchema;
import org.codehaus.stax2.validation.XMLValidationSchemaFactory;

import errorHandler.ParserStaxHandler;

public class woodstock {

	public long validateWoodstock(String xml, String xsd) throws XMLStreamException {
		// First, let's parse DTD schema object

		long startTime = System.nanoTime();

		XMLValidationSchemaFactory sf = XMLValidationSchemaFactory
				.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);

		File schemaFile = new File(xsd);
		XMLValidationSchema dtd = null;

//		try {
			dtd = sf.createSchema(schemaFile);
//		} catch (XMLStreamException xe) {
//			System.err.println("Failed to process the xsd file ('" + schemaFile
//					+ "'): " + xe);
//			System.exit(1);
//		}

		// And then validate a document:
		File inputFile = new File(xml);
		// try {
		XMLInputFactory2 ifact = (XMLInputFactory2) XMLInputFactory
				.newInstance();
		XMLStreamReader2 sr = ifact.createXMLStreamReader(inputFile);

		// try {
		sr.validateAgainst(dtd);
		sr.setValidationProblemHandler(new ParserStaxHandler());
		/*
		 * Document validation is done as document is read through (ie. it's
		 * fully streaming as well as parsing), so just need to traverse the
		 * contents.
		 */
		while (sr.hasNext()) {
			sr.next();
		}
		// } catch (XMLValidationException vex) {
		// System.err.println("Document '"+inputFile+"' failed validation: "+vex);
		// // long estimatedTime = System.nanoTime() - startTime;
		// // System.out.println("Total: "+ estimatedTime
		// +" nanosegundos usando Woodstock 4.1.4");
		// // System.exit(1);
		// }
		// } catch (XMLStreamException xse) {
		// System.err.println("Failed parse the input document ('"+inputFile+"'): "+xse);
		// // long estimatedTime = System.nanoTime() - startTime;
		// // System.out.println("Total: "+ estimatedTime
		// +" nanosegundos usando Woodstock 4.1.4");
		// // System.exit(1);
		// }
		// System.out.println("Document '"+inputFile+"' succesfully validated.");
		long estimatedTime = System.nanoTime() - startTime;
		System.out.println("Total: " + estimatedTime
				+ " nanosegundos usando Woodstock 4.1.4");
		return estimatedTime;

	}
}